package com.zzb.weixin.model.msg.basic;

import java.util.Date;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.zzb.weixin.constant.Constant.WXMsgType;
import com.zzb.weixin.constant.WXJsonName;
import com.zzb.weixin.constant.WXXmlElementName;
import com.zzb.weixin.json.JsonObject;

/**
 * 微信消息头
 * 
 * @author zzb
 * */
public class HeadMsg extends Msg {
	// 开发者微信号
	private String toUserName;
	// 发送方帐号（一个OpenID）
	private String fromUserName;
	// 消息创建时间 （整型）
	private Long createTime;
	// 消息类型：text\image\
	private WXMsgType msgType;

	/**
	 * 一般由程序内部调用，开发者不用调用
	 * */
	public HeadMsg() {
		this.createTime = new Date().getTime();// 初始化创建时间
	}
	public HeadMsg(Document document){
		this();
		setDocument(document);
		read();
	}

	public JsonObject toJson() {
		JsonObject jo = new JsonObject();
		jo.put(WXJsonName.TO_USER, toUserName);
		jo.put(WXJsonName.MSG_TYPE, msgType.toString());
		return jo;
	}

	public String getToUserName() {
		return toUserName;
	}

	public void setToUserName(String toUserName) {
		this.toUserName = toUserName;
	}

	public String getFromUserName() {
		return fromUserName;
	}

	public void setFromUserName(String fromUserName) {
		this.fromUserName = fromUserName;
	}

	public Long getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Long createTime) {
		this.createTime = createTime;
	}

	public WXMsgType getMsgType() {
		return msgType;
	}

	public void setMsgType(WXMsgType msgType) {
		this.msgType = msgType;
	}

	@Override
	public Element write() {
		Element xml = document.createElement(WXXmlElementName.XML);
		Element toUserNameElement = document
				.createElement(WXXmlElementName.TO_USER_NAME);
		toUserNameElement.setTextContent(this.toUserName);
		Element fromUserNameElement = document
				.createElement(WXXmlElementName.FROM_USER_NAME);
		fromUserNameElement.setTextContent(this.fromUserName);
		Element createTimeElement = document
				.createElement(WXXmlElementName.CREATE_TIME);
		createTimeElement.setTextContent(this.createTime.toString());
		Element msgTypeElement = document
				.createElement(WXXmlElementName.MSG_TYPE);
		msgTypeElement.setTextContent(this.msgType.toString());

		xml.appendChild(toUserNameElement);
		xml.appendChild(fromUserNameElement);
		xml.appendChild(createTimeElement);
		xml.appendChild(msgTypeElement);
		return xml;
	}

	@Override
	public void read() {
		this.toUserName = getElementContent(WXXmlElementName.TO_USER_NAME);
		this.fromUserName = getElementContent(WXXmlElementName.FROM_USER_NAME);
		this.createTime = Long
				.valueOf(getElementContent(WXXmlElementName.CREATE_TIME));
		this.msgType = WXMsgType.valueOf(getElementContent(WXXmlElementName.MSG_TYPE));

	}

}
